package model

import (
	"github.com/fatih/color"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gosh/config"
)

var DB *gorm.DB

func init() {
	if !config.GlobalConfig.UsedDB {
		return
	}
	db, err := gorm.Open(sqlite.Open(config.GlobalConfig.DBFile), &gorm.Config{
		SkipDefaultTransaction: true,
		Logger:                 logger.Default.LogMode(logger.Silent),
	})
	if err != nil {
		color.Yellow("Open database failed, err:%s", err.Error())
		return
	}

	if err = db.AutoMigrate(&Bastion{}); err != nil {
		color.Red("Migrate database %s failed, error:%s", "Bastion", err.Error())
	}

	if err = db.AutoMigrate(&Host{}); err != nil {
		color.Red("Migrate database %s failed, err:%s", "Host", err.Error())
	}

	DB = db
}
